package org.hit.burkun.umls.relation;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;
import org.hit.burkun.umls.GeneralQuery;
import org.hit.burkun.umls.relation.UniformRelation.TYPE;

public class StringRealtionAdapter {

	public static void main(String[] args) {
		Collection<UniformRelation> res = getGene2GeneRel();
		UniformRelationDump.dumpRelationsWithoutPrimaryId(res, false,
				"birelation");
	}

	public static Collection<UniformRelation> getGene2GeneRel() {
		DBHelper dbh = DBHelper.getLocalBioSearch();
		dbh.connectionDB();
		// 添加过滤条件，试验得分>0.4的才加入
		Collection<String[]> rawRes = dbh
				.queryData(
						"select gene1_ids, gene2_ids, combine_score from string_interactions_combine where experimental >= 0.4",
						3);
		dbh.disconnection();
		HashSet<String> terms = new HashSet<String>();
		for (String[] line : rawRes) {
			// 不考虑多个geneid在一起的情况了，太累了
			terms.add(line[0]);
			terms.add(line[1]);
		}
		// not update unmpapped
		GeneralQuery gq = new GeneralQuery(DBHelper.getServerData(),
				"map_umls_ids", false);
		gq.begin();
		gq.quickMap(terms, Entity.TYPE.GENE_ID);
		gq.end();
		Map<String, Set<String>> mapRes = gq.getResult();
		Collection<UniformRelation> res = new LinkedList<UniformRelation>();
		for (String[] line : rawRes) {
			if (mapRes.containsKey(line[0]) && mapRes.containsKey(line[1])) {
				Set<String> umls1 = mapRes.get(line[0]);
				Set<String> umls2 = mapRes.get(line[1]);
				String u1 = StringUtils.join(umls1, ",");
				String u2 = StringUtils.join(umls2, ",");
				Entity ent1 = new Entity(null, null, u1, line[0],
						Entity.TYPE.GENE_ID);
				Entity ent2 = new Entity(null, null, u2, line[1],
						Entity.TYPE.GENE_ID);
				TYPE type = TYPE.STRING_GENE;
				if (type != null) {
					//大bug！string是有向边
					UniformRelation ur = new UniformRelation(ent1, ent2, true,
							type);
					ur.setConfidscore(line[2]);
					res.add(ur);
				}
			}
		}
		return res;
	}
}
